<template>
  <view class="container">
    <web-view :src="systemUrl" style="width: 100%; height: 100%;" @message="handlePostMessage"/>
  </view>
</template>

<script>
import { executeSql, selectSql } from "@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/dbOrm/db/SqliteHelper";
import { initDb } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/app/application.ts';

export default {
  data() {
    return {
      // web-view支持的消息类型
      msgActions : ['createSql', 'addSql', 'updateSql', 'deleteSql'],
      systemUrl: ''
    };
  },
  onLoad(options) {
    this.systemUrl = decodeURIComponent(options.htmlPath);
    console.log('加载页面路径:', this.systemUrl);
  },
  methods: {
    // 向web-view发送消息
    evalJs(msg) {
      const webView = this.$scope.$getAppWebview().children()[0];
      webView.evalJS(`receiveMessageFromApp('${JSON.stringify(msg)}')`);
    },
    // 接收webview发来的消息
    async handlePostMessage(event) {
      console.log("接收到消息：" + JSON.stringify(event.detail));

      const {action, dbName, sql, requestId} = event.detail.data[0];

      let result;

      try {
        if (this.msgActions.includes(action)) {
          result = await executeSql(dbName, sql);
        } else if (action === 'selectSql') {
          result = await selectSql(dbName, sql);
        } else {
          result = "未知的 action 类型";
        }
      } catch (err) {
        console.error(`执行 ${action} 失败:`, err);
        result = action === 'selectSql' ? [] : false;
      }
      this.evalJs({ requestId, data: result });
    }
  }
};
</script>

<style scoped>
.container {
  width: 100%;
  height: 100vh;
}
</style>
